package com.wsjc.app.data;

import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.TransferQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.wsjc.app.data.core.DataPersist;
import com.wsjc.app.data.core.DataTask;


/**
 *  功能说明：同步数据到solr mq listener
 */
public class App 
{
	private static Logger logger = LoggerFactory.getLogger(App.class);

	public static TransferQueue<DataTask> tasks = new LinkedTransferQueue<DataTask>();

	private static ClassPathXmlApplicationContext context;

	private static ThreadPoolTaskExecutor threadPool;

	public static DataPersist dataPersist;

	public static void main(String[] args) {
		try {
			context = new ClassPathXmlApplicationContext(new String[] { "spring/spring-context.xml" });
			context.start();
			threadPool = (ThreadPoolTaskExecutor) context.getBean("threadPool");

			dataPersist = (DataPersist) context.getBean("dataPersist");
			dataPersist.initSolrDataLogFromDB(); // 从数据库中取一次数据用来当系统启动时初始化（此处可优化）

			startThread(); // 启动任务处理线程

			logger.info("app-data|starting...");
		} catch (Exception e) {
			logger.error("app-data|application start error:", e);
			return;
		}
		synchronized (App.class) {
			while (true) {
				try {
					App.class.wait();
				} catch (InterruptedException e) {
					logger.error("app-data|synchronized error:", e);
				}
			}
		}
	}

	/**
	 * 优化 线程的销毁 和 开辟所浪费的资源 PS : 2核 的cpu ,最大线程数设置4 ，核心设置为2 ，缓冲队列也是4
	 */
	private static void startThread() {
		logger.info("app-data|startThread...");

//		for (int i = 0; i < 1; i++) {
		for (int i = 0; i < threadPool.getMaxPoolSize(); i++) {

			threadPool.execute(new Runnable() {
				
				/** 当前执行次数 **/
			    int executeCount = 0;
				  
			    /** 默认最大执行次数 3 **/
			    int executeMaxCount = 3;
			    
				public void run() {
					try {
						while (true) {
							DataTask task = null ;
							if(executeCount == 0){
								Thread.sleep(1500);
								task = tasks.poll(); // 使用take方法获取过期任务,如果获取不到,就一直等待,知道获取到数据并删除
								logger.info("app-data|executeCount={}|剩余大小==>tasks.size={}:", executeCount, tasks.size());
							}
							if (task != null) {
								task.run(executeCount, executeMaxCount); // 执行更新data
							}
						}
					} catch (Exception e) {
						logger.error("app-data|task run error;", e);
					}
				}
			});
		}
	}
    

}
